<template>
  <div class="appointments-form">
    <el-card shadow="never">
      <template #header>
        <div class="page-header">
          <h2>{{ isEdit ? '编辑预约' : '添加预约' }}</h2>
          <el-button @click="$router.back()">返回</el-button>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        class="form-container"
      >
        <el-form-item label="客户编号" prop="userId">
          <el-input v-model.number="form.userId" placeholder="请输入客户姓名" />
        </el-form-item>
        <el-form-item label="宠物编号" prop="petId">
          <el-input v-model.number="form.petId" placeholder="请输入宠物姓名" />
            </el-form-item>
        <el-form-item label="服务项目编号" prop="serviceId">
          <el-input v-model.number="form.serviceId" placeholder="请输入服务项目" />
            </el-form-item>
        <el-form-item label="服务人员编号" prop="staffId">
          <el-input v-model.number="form.staffId" placeholder="请输入服务人员" />
            </el-form-item>
        <el-form-item label="使用资源编号" prop="resourceId">
          <el-input v-model.number="form.resourceId" placeholder="请输入使用服务资源" />
            </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker v-model="form.startTime" type="datetime" placeholder="选择开始时间" style="width: 100%;" />
            </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker v-model="form.endTime" type="datetime" placeholder="选择结束时间" style="width: 100%;" />
            </el-form-item>
        <el-form-item label="预约状态" prop="appointmentStatus">
          <el-input v-model="form.appointmentStatus" placeholder="请输入预约状态" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="loading">
            {{ isEdit ? '更新' : '保存' }}
          </el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { appointmentsApi } from '@/api'
import type { Appointments } from '@/types'

const router = useRouter()
const route = useRoute()

const formRef = ref<FormInstance>()
const loading = ref(false)

// 判断是否为编辑模式
const isEdit = computed(() => {
  return route.params.id !== undefined
})

// 表单数据
const form = reactive<Appointments>({
  userId: '',
  petId: undefined,
  serviceId: '',
  staffId: '',
  resourceId: '',
  startTime: '',
  endTime: '',
  appointmentStatus: ''
})

// 表单验证规则
const rules: FormRules = {
  userId: [
    { required: true, message: '请输入客户编号', trigger: 'change' }
  ],
  petId: [
    { required: true, message: '请输入宠物编号', trigger: 'change' }
  ],
  serviceId: [
    { required: true, message: '请输入服务项目编号', trigger: 'change' }
  ],
  staffId: [
    { required: true, message: '请输入服务人员编号', trigger: 'change' }
  ],
  resourceId: [
    { required: true, message: '请输入使用资源编号', trigger: 'change' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ],
  appointmentStatus: [
    { required: true, message: '请输入预约状态', trigger: 'change' }
  ]
}

// 获取预约详情
const fetchAppointmentDetail = async (id: number) => {
  try {
    const response = await appointmentsApi.getById(id)
    if (response.code === 200) {
      Object.assign(form, response.data)
    } else {
      ElMessage.error(response.message || '获取预约详情失败')
    }
  } catch (error) {
    console.error('获取预约详情失败:', error)
    ElMessage.error('获取预约详情失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    let response
    if (isEdit.value) {
      // 编辑模式，需要传入 appointmentId
      response = await appointmentsApi.update(form.appointmentId as number, form)
    } else {
      // 添加模式
      response = await appointmentsApi.add(form)
    }
    
    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
      router.push('/base/appointments')
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('提交表单失败:', error)
  } finally {
    loading.value = false
  }
}

// 取消操作
const handleCancel = () => {
  router.push('/base/appointments')
}

onMounted(() => {
  if (isEdit.value) {
    const appointmentId = Number(route.params.id)
    if (appointmentId) {
      fetchAppointmentDetail(appointmentId)
    }
  }
})
</script>

<style scoped>
.appointments-form {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.form-container {
  max-width: 800px;
  margin: 0 auto;
}
</style> 